package org.bt4girls.oauth.service.impl;

import org.bt4girls.common.model.dto.UserBaseDTO;
import org.bt4girls.common.model.result.ErrorCode;
import org.bt4girls.common.model.result.ServiceResult;
import org.bt4girls.common.model.oauth.TbUserBase;
import org.bt4girls.common.utils.JwtUtils;
import org.bt4girls.common.utils.PasswordUtils;
import org.bt4girls.oauth.mappy.TbUserBaseMapper;
import org.bt4girls.oauth.mappy.TbUserPermissionMapper;
import org.bt4girls.oauth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

public class UserServiceImpl implements UserService {
    @Autowired
    private TbUserBaseMapper userBaseMapper;
    @Autowired
    private TbUserPermissionMapper userPermissionMapper;

    @Override
    public ServiceResult<UserBaseDTO> baseUserLogin(String username, String password, String loginIp) {
        TbUserBase user = userBaseMapper.selectBaseByUsername(username);
        if (user == null) {
            return ServiceResult.exception(ErrorCode.OAUTH_USER_NO_EXIST_OR_PWD_ERROR, null);
        }
        if (!PasswordUtils.checkUserPwd(password, user.getPassword())) {
            return ServiceResult.exception(ErrorCode.OAUTH_USER_NO_EXIST_OR_PWD_ERROR, null);
        }
        UserBaseDTO dto = new UserBaseDTO();
        String refreshToken = JwtUtils.generateRefreshToken();
        // TODO: 2020/9/16  refreshToken入库
        dto.setUser(userBaseMapper.selectByPrimaryKey(user.getId()))
                .setPermission(userPermissionMapper.selectPermissionByUid(user.getId()))
                .setAccessToken(JwtUtils.generateUserJwt(user.getId(), username))
                .setRefreshToken(JwtUtils.generateRefreshToken());
        return ServiceResult.success(dto);
    }
}
